'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const { INTEGER, DATE } = Sequelize;
    
    await queryInterface.createTable('sys_role_menus', {
      id: {
        type: Sequelize.BIGINT,
        primaryKey: true,
        comment: '关联ID',
      },
      role_code: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: '角色编码',
        references: {
          model: 'sys_roles',
          key: 'code',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      menu_id: {
        type: Sequelize.BIGINT,
        allowNull: false,
        comment: '菜单ID',
        references: {
          model: 'sys_menus',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      create_time: {
        type: DATE,
        allowNull: false,
        comment: '创建时间',
      },
      update_time: {
        type: DATE,
        allowNull: false,
        comment: '更新时间',
      },
    });
    
    // 添加复合唯一索引，确保角色和菜单的组合唯一
    await queryInterface.addIndex('sys_role_menus', ['role_code', 'menu_id'], {
      unique: true,
      name: 'role_menu_unique',
    });
    
    // 添加普通索引
    await queryInterface.addIndex('sys_role_menus', ['role_code']);
    await queryInterface.addIndex('sys_role_menus', ['menu_id']);
  },

  down: async (queryInterface, Sequelize) => {
    // 先删除外键约束
    await queryInterface.removeConstraint('sys_role_menus', 'sys_role_menus_ibfk_1');
    await queryInterface.removeConstraint('sys_role_menus', 'sys_role_menus_ibfk_2');
    // 再删除索引
    await queryInterface.removeIndex('sys_role_menus', 'role_menu_unique');
    await queryInterface.removeIndex('sys_role_menus', 'sys_role_menus_menu_id');
    // 最后删除表
    await queryInterface.dropTable('sys_role_menus');
  },
};